package com.anthonybennis.blender.client;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;

/**
 * 
 * @author Anthony
 */
public class Util 
{
	/**
	 * 
	 * @param panel
	 */
	public static void centerWidget(Widget panel)
	{
		panel.getElement().getStyle().setProperty("marginLeft", "auto");
		panel.getElement().getStyle().setProperty("marginRight", "auto");
		panel.getElement().getStyle().setProperty("marginTop", "auto");
		panel.getElement().getStyle().setProperty("marginBottom", "auto");
	}
	
	/**
	 * Util.centerWidget() does not work in every situation. For example, the main Widget
	 * of a DockLayoutPanel requires this method to center it's contents.
	 *  
	 * @param widget
	 * @return Flexitable, which wraps your widget
	 */
	public static Widget createCenteredWrappedWidget(Widget widget)
	{
		FlexTable wrapper = new FlexTable();
		wrapper.setSize("100%", "100%");
		wrapper.setWidget(0, 0, widget);
		wrapper.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE);
		wrapper.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
		
		return wrapper;
	}
	
	/**
	 * 
	 * @param widget
	 * @param colour
	 */
	public static void setBackground(Widget widget, String colour)
	{
		widget.getElement().getStyle().setBackgroundColor(colour);
	}
	
	public static void setFontColour(Widget widgtWithText, String colour)
	{
		widgtWithText.getElement().getStyle().setColor(colour);
	}
	
	public static String RGBToHex(int r, int g, int b)
	{
	      StringBuilder sb = new StringBuilder();
	      sb.append('#')
	      .append(Integer.toHexString(r))
	      .append(Integer.toHexString(g))
	      .append(Integer.toHexString(b));
	      return sb.toString();
	 }
	
	public static void scaleImage(Image image, int width, int hieght)
	{
		image.setHeight(hieght + "px");
		image.setWidth(width + "px");
		image.setPixelSize(width, hieght);
	}
	
	public static Widget getWidget(Element element) 
	{
	    EventListener listener = DOM.getEventListener((Element) element);
	    /*
	     * No listener attached to the element, so no widget exist for this element.
	     */
	    if (listener == null) 
	    {
	        return null;
	    }
	    
	    if (listener instanceof Widget) 
	    {
	        // GWT uses the widget as event listener
	        return (Widget) listener;
	    }
	    
	    return null;
	}
}